package com.magnate.software.mongo.db.aop;

import com.magnate.software.mongo.db.context.PagingContextHolder;
import com.magnate.software.mongo.db.domain.Page;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

/**
 * 分页查询
 *
 * @author WangYang
 * @version 1.0
 * @datetime 2016/11/30 17:02
 */
@Aspect
@Service("mongoPagingAdvices")
public class MongoPagingAdvices {

    @Pointcut("execution (* org.springframework.data.mongodb.core.MongoTemplate.find(..))")
    public void pointCut() {

    }

    @Before("pointCut()")
    public void before(JoinPoint joinPoint) {
        MongoTemplate mongoTemplate = (MongoTemplate) joinPoint.getThis();
        // 翻页参数
        Page page = PagingContextHolder.getPage();
        if (page != null) {
            Object[] args = joinPoint.getArgs();
            Query query = (Query) args[0];

            long count = mongoTemplate.count(query, (Class) args[1]);
            page.setTotalResult(count);

            System.out.println(count);

            query.limit((int) page.getPageSize());
            query.skip((int) (page.getCurrentPage() * page.getPageSize()));
            args[0] = query;
        }

    }

}
